﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Srvtools;


public partial class WorkTime_ViewWorkOn2Pay : System.Web.UI.Page
{
    private Srvtools.WebDataSet wsViewDepWorkOnCheck;
    private Hashtable EmpWorkOnDateTable;
    private Hashtable CompWorkDateDefine;
    private Hashtable EmpOverTimeDateTable;
    private Hashtable WorkTimeLeaveTypeDefine;
    private DataSet EmpLeaveDate;

    private string StartWorkOn;
    private string EndWorkOn;
    private string LateOfStartTime;
    private string LeaveOfEndTime;

    private DateTime FirstDayOfThisMonth;
    private DateTime LastDayOfThisMonth;
    private string StartDateKey = "";
    private string EndDataKey = "";


    private void InitializeComponent()
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WorkTime_ViewWorkOn2Pay));
        this.wsViewDepWorkOnCheck = new Srvtools.WebDataSet();
        ((System.ComponentModel.ISupportInitialize)(this.wsViewDepWorkOnCheck)).BeginInit();
        // 
        // wsViewDepWorkOnCheck
        // 
        this.wsViewDepWorkOnCheck.Active = false;
        this.wsViewDepWorkOnCheck.AlwaysClose = false;
        this.wsViewDepWorkOnCheck.DeleteIncomplete = true;
        this.wsViewDepWorkOnCheck.Guid = "5abc890f-29be-408a-bb92-77dcb8bb9319";
        this.wsViewDepWorkOnCheck.LastKeyValues = null;
        this.wsViewDepWorkOnCheck.Locale = new System.Globalization.CultureInfo("zh-CN");
        this.wsViewDepWorkOnCheck.PacketRecords = 100;
        this.wsViewDepWorkOnCheck.Position = -1;
        this.wsViewDepWorkOnCheck.RemoteName = "SWorkTime.View_WorkTime_Overtime";
        this.wsViewDepWorkOnCheck.ServerModify = false;
        ((System.ComponentModel.ISupportInitialize)(this.wsViewDepWorkOnCheck)).EndInit();

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            int year = DateTime.Now.Year;
            int Month = DateTime.Now.Month;

            DlYear.SelectedValue = year.ToString();
            DLMonth.SelectedValue = Month.ToString();


            MasterPage_MasterPage mpg = (MasterPage_MasterPage)this.Page.Master;
            mpg.HelpHref = "~/Help/WorkTime/查看员工计算工资的考勤数据.htm";
            mpg.PageName = "查看员工计算工资的考勤数据";
            mpg.PicUrl = "";
            mpg.IntiBar();
        }
    }

    protected void MakeDataSet(String SelDepId)
    {
        InitializeComponent();

        //get the WorkOn data
        DataSet EmpList;
        string sSql;

        sSql = " SELECT Employees.EmployeeID, Employees.EmpName, Department.DepartmentName ";
        sSql = sSql + "FROM  Employees INNER JOIN Department ON Employees.DepartmentId = Department.DepartmentId ";
        sSql = sSql + string.Format("WHERE (Employees.EmpStatus = 1) AND (Employees.DepartmentId LIKE '{0}%') ", SelDepId);
        sSql = sSql + " ORDER BY Employees.DepartmentId ";
        EmpList = wsViewDepWorkOnCheck.Execute(sSql);


        DataTable svTable;
        svTable = MakeNewWTable();
        DataRow SR;

        string EmpId = "";
        string EmpName = "";
        string Daykey = "";
        string DepartmentName = "";

        for (int i = 0; i < EmpList.Tables[0].Rows.Count; i++)
        {

            EmpId = (string)EmpList.Tables[0].Rows[i]["EmployeeID"].ToString().Trim();
            EmpName = (string)EmpList.Tables[0].Rows[i]["EmpName"];
            DepartmentName = (string)EmpList.Tables[0].Rows[i]["DepartmentName"];


            DateTime sDate = FirstDayOfThisMonth;
            DateTime eDate = LastDayOfThisMonth;
            Hashtable OverTimeTableCol = new Hashtable();
            Single OverTimeHours = 0;

            Single OverTimeG = 0; //日常加班
            Single OverTimeV = 0; //双修日加班
            Single OverTimeH = 0; //节假日加班
            Single AllOverTimeD = 0;//所有加班乘系数值
            string LeaveTime = "";
            string SpecialTime = "";


            while (sDate <= eDate)
            {
                Daykey = sDate.Year.ToString().Trim() + "-" + sDate.Month.ToString().Trim() + "-" + sDate.Day.ToString().Trim();
                string DKey = EmpId + "-" + Daykey;
                Single DayCC;
                bool NowIsWorkingDay = IsWorkingDay(sDate, out  DayCC);

                // Single OutHour = 0;


                //int Dtyp;

                //计算加班
                if (EmpOverTimeDateTable.ContainsKey(DKey))
                {
                    object[] DtIn = (object[])EmpOverTimeDateTable[DKey];
                    OverTimeHours = Convert.ToSingle(DtIn[2]);
                    switch (Convert.ToInt32(DayCC * 10))
                    {
                        case 20:
                            OverTimeV = OverTimeV + OverTimeHours;
                            AllOverTimeD = AllOverTimeD + DayCC * OverTimeHours;
                            break;
                        case 30:
                            OverTimeH = OverTimeH + OverTimeHours;
                            AllOverTimeD = AllOverTimeD + DayCC * OverTimeHours;
                            break;
                        default:
                            OverTimeG = OverTimeG + OverTimeHours;
                            AllOverTimeD = AllOverTimeD + DayCC * OverTimeHours;
                            break;
                    }
                    // ShowThisRow = true;
                }


                if (NowIsWorkingDay == false) //非工作日
                {
                    //
                }
                else  //工作日
                {
                    if (EmpWorkOnDateTable.ContainsKey(DKey))
                    {
                        DateTime[] DtIn = (DateTime[])EmpWorkOnDateTable[DKey];
                        Single WorkHour = 0;
                        int IsAbsence = IsWorkingAbsence(Daykey, DtIn[0], DtIn[1], out WorkHour);
                        if (IsAbsence == 0)//是否缺迟到,早退
                        {
                            //
                        }
                        else
                        {
                            TimeSpan NTd = (DtIn[1] - DtIn[0]);
                            Single Dhour = WorkingOutTime(EmpId, Daykey, ref OverTimeTableCol);

                            //Dhour = 0;
                            ////处理请假数据
                            //if (OverTimeTableCol.Count > 0)
                            //{
                            //    foreach (string LKey in OverTimeTableCol.Keys)
                            //    {
                            //        Dhour = Dhour + Convert.ToSingle( OverTimeTableCol[LKey]);
                            //       // LeaveTime = LeaveTime + KeyName + OverTimeTableCol[LKey] + "小时;";
                            //    }
                            //}

                            Dhour = WorkHour + Dhour;

                            if (Dhour < 8) //缺工作时间
                            {
                                SpecialTime = SpecialTime + sDate.Day.ToString() + "日缺" + (8 - Dhour).ToString(".##") + "小时;";
                                //  ShowThisRow = true;
                            }
                        }
                    }
                    else
                    {
                        Single Dhour = WorkingOutTime(EmpId, Daykey, ref OverTimeTableCol);

                        if (Dhour < 7.8)
                        {
                            SpecialTime = SpecialTime + sDate.Day.ToString() + "日缺" + (8 - Dhour).ToString(".##") + "小时;";
                            // ShowThisRow = true;
                        }

                    }
                }

                sDate = sDate.AddDays(1);
            }

            //处理请假数据
            if (OverTimeTableCol.Count > 0)
            {
                foreach (string LKey in OverTimeTableCol.Keys)
                {
                    string KeyName = "";
                    if (WorkTimeLeaveTypeDefine.ContainsKey(LKey) == true)
                    {
                        object[] DtIn = (object[])WorkTimeLeaveTypeDefine[LKey];
                        KeyName = Convert.ToString(DtIn[0]);
                    }
                    else
                    {
                        KeyName = LKey;
                    }
                    LeaveTime = LeaveTime + KeyName + OverTimeTableCol[LKey] + "小时;";
                }
            }


            SR = svTable.NewRow();

            SR["EmployeeID"] = EmpId;
            SR["EmpName"] = EmpName;
            SR["DepartmentName"] = DepartmentName;

            SR["Month"] = DLMonth.SelectedValue + "月";   //sDate.Month.ToString() + "月";
            SR["OverTimeG"] = OverTimeG;
            SR["OverTimeV"] = OverTimeV;
            SR["OverTimeH"] = OverTimeH;
            SR["AllOverTimeD"] = AllOverTimeD;

            SR["LeaveTime"] = LeaveTime;
            if (ShowWorkOn.Checked == true) SR["SpecialTime"] = SpecialTime;

            svTable.Rows.Add(SR);

        }

        wgvMaster.DataSource = svTable;
        wgvMaster.DataBind();

    }


    private DataTable MakeNewWTable()
    {
        DataTable WTable = new DataTable("EmpYearTable");

        {
            WTable.Columns.Add(new DataColumn("EmployeeID", typeof(Int32)));
            WTable.Columns.Add(new DataColumn("EmpName", typeof(string)));
            WTable.Columns.Add(new DataColumn("DepartmentName", typeof(string)));

            WTable.Columns.Add(new DataColumn("Month", typeof(string)));
            WTable.Columns.Add(new DataColumn("OverTimeG", typeof(Single))); //日常加班
            WTable.Columns.Add(new DataColumn("OverTimeV", typeof(Single)));//双修日加班
            WTable.Columns.Add(new DataColumn("OverTimeH", typeof(Single)));//节假日加班
            WTable.Columns.Add(new DataColumn("AllOverTimeD", typeof(Single)));//所有加班乘系数值

            WTable.Columns.Add(new DataColumn("LeaveTime", typeof(string)));
            WTable.Columns.Add(new DataColumn("SpecialTime", typeof(string)));
        }
        return WTable;
    }


    protected void Refresh_Click(object sender, EventArgs e)
    {
        string SelDepId = DepartmentDList1.SelectDepmanetId;
        if (SelDepId.Length > 0 && SelDepId != "0")
        {
            int year = int.Parse(DlYear.SelectedValue);
            int month = int.Parse(DLMonth.SelectedValue);
            FirstDayOfThisMonth = new DateTime(year, month, 1);
            LastDayOfThisMonth = new DateTime(year, month, DateTime.DaysInMonth(year, month));


            StartDateKey = FirstDayOfThisMonth.Year.ToString().Trim() + "-" + FirstDayOfThisMonth.Month.ToString().Trim() + "-" + FirstDayOfThisMonth.Day.ToString().Trim();
            EndDataKey = LastDayOfThisMonth.Year.ToString().Trim() + "-" + LastDayOfThisMonth.Month.ToString().Trim() + "-" + LastDayOfThisMonth.Day.ToString().Trim();

            DoWorkOnInit(StartDateKey, EndDataKey);
            GetData(SelDepId, StartDateKey, EndDataKey);

            MakeDataSet(SelDepId);
        }
        else
        {
            string message = "请首先选择部门!";
            // this.Page.Response.Write("<script>alert(\"" + message + "\");</script>");
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"" + message + "\");", true);
        }

    }

    #region 工作时间分析

    /// <summary>
    /// 设置员工分析初试化数据
    /// </summary>
    /// <param name="DateS">本月起始日</param>
    /// <param name="DataE">本月终止日</param>
    private void DoWorkOnInit(string DateS, string DataE)
    {

        StartWorkOn = ConfigurationManager.AppSettings["StartTimeOfWorkOnTime"];
        EndWorkOn = ConfigurationManager.AppSettings["EndTimeOfWorkOnTime"];
        LateOfStartTime = ConfigurationManager.AppSettings["LateOfStartTime"];
        LeaveOfEndTime = ConfigurationManager.AppSettings["LeaveOfEndTime"];

        //取得公司工作日期定义的数据集合
        object[] objParam2 = new object[2];
        objParam2[0] = DateS;
        objParam2[1] = DataE;
        object[] myRet2 = CliUtils.CallMethod("SWorkTime", "GetCompWorkDateDefine", objParam2);
        if (myRet2 != null && (int)myRet2[0] == 0)
        {
            CompWorkDateDefine = (Hashtable)myRet2[1];
        }

        //取得请假类型的数据集合
        object[] objParam = new object[0];
        object[] myRet = CliUtils.CallMethod("SWorkTime", "GetWorkTime_SV_LeaveType", objParam);
        if (myRet != null && (int)myRet[0] == 0)
        {
            WorkTimeLeaveTypeDefine = (Hashtable)myRet[1];
        }

    }


    /// <summary>
    /// 取得本月某员工的的考勤和公司日期定义日的集合
    /// </summary>
    /// <param name="EmpId">员工工号</param>
    /// <param name="DateS">本月起始日</param>
    /// <param name="DataE">本月终止日</param>
    private void GetData(string depId, string DateS, string DataE)
    {
        object[] objParam = new object[3];
        objParam[0] = depId;
        objParam[1] = DateS;
        objParam[2] = DataE;
        object[] myRet = CliUtils.CallMethod("SWorkTime", "GetEmpWorkOnDateTableByDeparment", objParam);
        if (myRet != null && (int)myRet[0] == 0)
        {
            EmpWorkOnDateTable = (Hashtable)myRet[1];
        }

        object[] myRet3 = CliUtils.CallMethod("SWorkTime", "GetEmpWorkOvertimeDateByDeparment", objParam);
        if (myRet3 != null && (int)myRet3[0] == 0)
        {
            EmpOverTimeDateTable = (Hashtable)myRet3[1];
        }

        object[] myRet4 = CliUtils.CallMethod("SWorkTime", "GetEmpLeaveDateByDeparment", objParam);
        if (myRet4 != null && (int)myRet4[0] == 0)
        {
            EmpLeaveDate = (DataSet)myRet4[1];
        }

    }

    /// <summary>
    /// 取得某一日期下外出,请假,出差的时间
    /// </summary>
    /// <param name="DayKey">某一日期</param>
    /// <param name="DayHour">返回的时间数</param>
    /// <returns>返回外出的类型:请假=1,出差=2,公出=3</returns>
    private Single WorkingOutTime(string EmpId, string DayKey, ref Hashtable OverTimeTableCol)
    {
        Single LeaveHourN = 0;
        Single EvectionN = 0;
        Single OutHourN = 0;
        //Hashtable OverTimeT = new Hashtable();

        int RDtyp = 0;
        if (EmpLeaveDate.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < EmpLeaveDate.Tables[0].Rows.Count; i++)
            {
                string dEmpId = (string)EmpLeaveDate.Tables[0].Rows[i]["EmployeeId"].ToString().Trim();
                int DTyp = (int)EmpLeaveDate.Tables[0].Rows[i]["DTyp"];
                if (dEmpId == EmpId)
                {
                    RDtyp = DTyp;
                    switch (DTyp)
                    {
                        case 1: // do -- WorkTime_Leave
                            DateTime DateS = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateFrom"];
                            DateTime DateE = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateTo"];
                            int LeaveTypeId = Convert.ToInt32(EmpLeaveDate.Tables[0].Rows[i]["LLeaveType"]);
                            int LeaHours = Convert.ToInt32(EmpLeaveDate.Tables[0].Rows[i]["LeaHours"]);
                            Single Ott = GetDateDayDiff(DayKey, DateS, DateE);
                            if (Ott > 0.1) //
                            {
                                LeaveHourN = LeaveHourN + Ott;
                                if (LeaveHourN > 0.1)
                                {
                                    string Ekey = LeaveTypeId.ToString().Trim();
                                    if (OverTimeTableCol.ContainsKey(Ekey) == false)
                                    {
                                        OverTimeTableCol.Add(Ekey, Ott);//LeaveHourN
                                    }
                                    else
                                    {
                                        OverTimeTableCol[Ekey] = Ott + Convert.ToSingle(OverTimeTableCol[Ekey]);
                                        //LeaveHourN
                                    }
                                }
                            }
                            break;
                        case 2: // do -- WorkTime_Evection
                            DateTime DateS2 = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateFrom"];
                            DateTime DateE2 = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateTo"];
                            EvectionN = EvectionN + GetDateDayDiff(DayKey, DateS2, DateE2);
                            break;
                        case 3: // do -- WorkTime_Out
                            DateTime DateS3 = (DateTime)EmpLeaveDate.Tables[0].Rows[i]["DateFrom"];
                            string DaykeyIn = DateS3.Year.ToString().Trim() + "-" + DateS3.Month.ToString().Trim() + "-" + DateS3.Day.ToString().Trim();
                            if (DaykeyIn == DayKey)
                            {
                                int Dsh = (int)EmpLeaveDate.Tables[0].Rows[i]["OutHour"];
                                int DsM = (int)EmpLeaveDate.Tables[0].Rows[i]["OutSecond"];
                                int DEh = (int)EmpLeaveDate.Tables[0].Rows[i]["BackHour"];
                                int DEM = (int)EmpLeaveDate.Tables[0].Rows[i]["BackSecond"];
                                OutHourN = OutHourN + (DEh - Dsh) + (DEM - DsM) / 60;
                            }
                            break;
                    }
                }
            }
        }

        Single Dhour = LeaveHourN + EvectionN + OutHourN;
        if (Dhour < -8.0) Dhour = -8.0f;
        // OverTimeTableCol = OverTimeT;
        return Dhour;
    }

    /// <summary>
    /// 取得某一日期下请假,出差的时间数
    /// </summary>
    /// <param name="DayKey">某一日期</param>
    /// <param name="DateS">请假,出差的起始时间</param>
    /// <param name="DateE">请假,出差的终止时间</param>
    /// <returns>请假,出差的时间数</returns>
    private Single GetDateDayDiff(string DayKey, DateTime DateS, DateTime DateE)
    {
        DateTime DateSS = DateTime.Parse(DayKey + " " + StartWorkOn);
        DateTime DateEE = DateTime.Parse(DayKey + " " + EndWorkOn);
        DateTime ltDateSS = DateTime.Parse(DayKey + " " + LateOfStartTime);
        DateTime ltDateEE = DateTime.Parse(DayKey + " " + LeaveOfEndTime);
        double Ret = 0;
        if (((DateSS >= DateS) && (DateSS <= DateE)) || ((DateEE >= DateS) && (DateEE <= DateE)))
        {
            if (DateS <= ltDateSS && ltDateEE <= DateE) //1整天
            { return (Single)8; }
            else if (DateS <= DateSS && DateEE >= DateE)//
            {
                TimeSpan NTd = (DateE - DateSS);
                Ret = (Single)NTd.Hours + Convert.ToDouble(NTd.Minutes) / 60.0;
                return (Single)Ret;

            }
            else if (DateS >= ltDateSS && ltDateEE >= DateE)//
            {
                TimeSpan NTd = (DateE - DateS);
                Ret = (Single)NTd.Hours + Convert.ToDouble(NTd.Minutes) / 60.0;
                return (Single)Ret;

            }
            else if (DateS >= ltDateSS && ltDateEE <= DateE)//
            {
                TimeSpan NTd = (DateEE - DateS);
                Ret = (Single)NTd.Hours + Convert.ToDouble(NTd.Minutes) / 60.0;
                return (Single)Ret;
            }
            else
            {
                return (Single)0;

            }
        }
        else
        {
            return (Single)0;
        }
    }

    /// <summary>
    /// 判断是否工作日缺席(迟到,早退)
    /// </summary>
    /// <param name="DayKey">当前日期</param>
    /// <param name="DateS">开始时间</param>
    /// <param name="DateE">终止时间</param>
    /// <param name="DayHour">终止时间</param>
    /// <returns>返回外出的类型:迟到=1,早退=2,迟到+早退=3,0=正常</returns>
    private int IsWorkingAbsence(string DayKey, DateTime DateS, DateTime DateE, out Single DayHour)
    {
        DateTime DateSS = DateTime.Parse(DayKey + " " + LateOfStartTime);
        DateTime DateEE = DateTime.Parse(DayKey + " " + LeaveOfEndTime);
        double Ret = 0;

        if (DateS > DateSS && DateEE < DateE) //迟到
        {
            DateTime StDateSS = DateTime.Parse(DayKey + " " + StartWorkOn);
            TimeSpan NTd = (DateS - StDateSS);
            Ret = (Single)8 - Convert.ToDouble(NTd.Hours) - Convert.ToDouble(NTd.Minutes) / 60;
            if (Ret < 0) Ret = 0;
            DayHour = (Single)Ret;
            return 1;
        }
        else if (DateS < DateSS && DateEE > DateE) //早退
        {
            DateTime StDateEE = DateTime.Parse(DayKey + " " + EndWorkOn);
            TimeSpan NTd = (StDateEE - DateE);
            Ret = (Single)8 - Convert.ToDouble(NTd.Hours) - Convert.ToDouble(NTd.Minutes) / 60.0;
            if (Ret < 0) Ret = 0;
            DayHour = (Single)Ret;
            return 2;
        }
        else if (DateS > DateSS && DateEE > DateE) //迟到+早退
        {
            DateTime StDateSS = DateTime.Parse(DayKey + " " + StartWorkOn);
            DateTime StDateEE = DateTime.Parse(DayKey + " " + EndWorkOn);
            TimeSpan NTd = (DateS - StDateSS);
            TimeSpan NTd2 = (StDateEE - DateE);
            Ret = (Single)8 - Convert.ToDouble(NTd.Hours) - Convert.ToDouble(NTd.Minutes) / 60.0 - Convert.ToDouble(NTd2.Hours) - Convert.ToDouble(NTd2.Minutes) / 60;
            if (Ret < 0) Ret = 0;
            DayHour = (Single)Ret;
            return 3;
        }
        else
        {
            DayHour = 8;
            return 0;
        }

    }


    /// <summary>
    /// 判断是否为工作日
    /// </summary>
    /// <param name="Inday"></param>
    /// <returns></returns>
    private bool IsWorkingDay(DateTime Inday, out Single DayCC)
    {
        int DatePeptry;
        string DKey = Inday.Year.ToString().Trim() + "-" + Inday.Month.ToString().Trim() + "-" + Inday.Day.ToString().Trim();
        DayCC = 1.5f;

        if (Inday.DayOfWeek == DayOfWeek.Saturday || Inday.DayOfWeek == DayOfWeek.Sunday)
        {
            if (CompWorkDateDefine.ContainsKey(DKey) == false)
            {
                DatePeptry = 0;
                DayCC = 2.0f;// = "双休日";
                return false;
            }
            else
            {
                object[] DtIn = (object[])CompWorkDateDefine[DKey];
                bool Dbk = (bool)DtIn[0];
                DatePeptry = (int)DtIn[1];

                switch (DatePeptry)
                {
                    case 1:
                        DayCC = 1.5f;// "工作日";
                        break;
                    case 2:
                        DayCC = 3.0f;// "法定假日";
                        break;
                    case 3:
                        DayCC = 1.5f;//;
                        break;
                    default:
                        DayCC = 1.5f;//;
                        break;
                }

                return Dbk;
            }
        }
        else
        {
            if (CompWorkDateDefine.ContainsKey(DKey) == false)
            {
                DatePeptry = 0;
                DayCC = 1.5f;// "工作日";
                return true;
            }
            else
            {
                object[] DtIn = (object[])CompWorkDateDefine[DKey];
                bool Dbk = (bool)DtIn[0];
                DatePeptry = (int)DtIn[1];
                switch (DatePeptry)
                {
                    case 1:
                        DayCC = 1.5f;// "工作日";
                        break;
                    case 2:
                        DayCC = 3.0f;// "法定假日";
                        break;
                    case 3:
                        DayCC = 2.0f;// "休息日";
                        break;
                    default:
                        DayCC = 1.5f;//;
                        break;
                }
                return Dbk;
            }
        }

    }
    #endregion
}
